package com.jz.community.modulemine.wifi.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.ShareInfo;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.reflection.share.ShareActionReflectUtils;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.DES;
import com.jz.community.basecomm.utils.DateUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.wifi.bean.WifiDayInfo;
import com.jz.community.modulemine.wifi.bean.WifiStateInfo;
import com.jz.community.modulemine.wifi.task.CheckWifiStateTask;
import com.jz.community.modulemine.wifi.task.GetWifiAccoutTask;
import com.jz.community.modulemine.wifi.task.GetWifiDayTask;
import com.jz.community.modulemine.wifi.task.GetWifiLogoutTask;
import com.jz.community.modulemine.wifi.task.GetWifiPwdTask;
import com.jz.community.modulemine.wifi.task.UpdateWifiDayTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;

import static com.jz.community.basecomm.utils.MD5.md5;

/**
 * Created by Tony.Fan on 2018/6/19 14:45
 */
public class MyWifiActivity extends BaseMvpActivity {

    @BindView(R2.id.title_back)
    ImageButton titleBack;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.tv_wifi_all_day)
    TextView tvWifiAllDay;
    @BindView(R2.id.tv_wifi_activity_remind)
    TextView tvWifiActivityRemind;
    @BindView(R2.id.ll_wifi_activity_and_all_day)
    LinearLayout llWifiActivityAndAllDay;
    @BindView(R2.id.iv_round_anim)
    ImageView ivRoundAnim;
    @BindView(R2.id.btn_connect_wifi)
    Button btnConnectWifi;
    @BindView(R2.id.iv_first_remind)
    ImageView ivFirstRemind;
    @BindView(R2.id.RL_connect_btn)
    RelativeLayout RLConnectBtn;
    @BindView(R2.id.connect_state_logo)
    ImageView connectStateLogo;
    @BindView(R2.id.tv_connect_state)
    TextView tvConnectState;
    @BindView(R2.id.ll_connect_state)
    LinearLayout llConnectState;
    @BindView(R2.id.tv_wifi_user_time)
    TextView tvWifiUserTime;
    @BindView(R2.id.cv_countdownView)
    CountdownView cvCountdownView;
    @BindView(R2.id.ll_internet_time)
    LinearLayout llInternetTime;
    @BindView(R2.id.community_wifi_name)
    TextView communityWifiName;
    @BindView(R2.id.btn_jump_first)
    Button btnJumpFirst;
    @BindView(R2.id.remind_pop)
    LinearLayout remindPop;

    private BroadcastReceiver broadcastReceiver;
    private Animation operatingAnim;
    private long currentTime, endTime, dayMill, currentTimeNow, lastTime;
    private LoginBaseInfo loginBaseInfo;
    private boolean isWifiSuccess = false;
    private WifiDayInfo wifiDayInfo;

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_connect_wifi;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(titleToolbar);
        titleName.setText("智慧社区WIFI");
        initWifiAnim();
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        loginBaseInfo = BaseSpUtils.getInstance().getUserBaseInfo(this);
        wifiBroadcastReceiver();
        getWifiDay();
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWifiAnim() {
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.connect_wifi_btn_anim);
        operatingAnim.setInterpolator(new LinearInterpolator());
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @OnClick(R2.id.btn_jump_first)
    public void btnWifiShareClick() {
        shareWifi();
    }

    @OnClick(R2.id.btn_connect_wifi)
    public void btnConnectWifiClick() {
        if (!Preconditions.isNullOrEmpty(wifiDayInfo)) {
            if (isWifiSuccess) {
                getWifiLogout();
            } else {
                SHelper.gone(ivFirstRemind);
                startAnimAndCheckWifiState();
            }
        } else {
            showWifiState("未连接");
        }
    }

    private void getWifiLogout() {
        new GetWifiLogoutTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {

            }
        }).execute();
    }

    private void wifiBroadcastReceiver() {
        if (broadcastReceiver == null) {
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (!CommUtils.checkWifiStatus(context)) {
                        offWifiRefreshPage();
                    }
                }
            };
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(broadcastReceiver, intentFilter);
        }
    }

    private void getWifiDay() {
        new GetWifiDayTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                wifiDayInfo = (WifiDayInfo) o;
                if (!Preconditions.isNullOrEmpty(wifiDayInfo)) {
                    tvWifiAllDay.setText("剩余" + wifiDayInfo.getRe_result().getAllDay() + "天");
                    if (!Preconditions.isNullOrEmpty(wifiDayInfo.getRe_result().getActivity())) {
                        tvWifiActivityRemind.setVisibility(View.VISIBLE);
                        tvWifiActivityRemind.setText(wifiDayInfo.getRe_result().getActivity().getDescrib());
                        if (CommUtils.isWifiOpen(MyWifiActivity.this)) {
                            startAnimAndCheckWifiState();
                        } else {
                            showOpenWifiPop();
                        }
                    } else {
                        tvWifiActivityRemind.setVisibility(View.GONE);
                    }
                } else {
                    tvWifiAllDay.setText("剩余0天");
                    showWifiState("未连接");
                }
            }
        }).execute(loginBaseInfo.getMobi());
    }

    private void showOpenWifiPop() {
       AlertDialog alertDialog =new AlertDialog.Builder(this).setTitle("开启Wi-Fi")
                .setMessage("请手动开启Wi-Fi!")//设置显示的内容  
                .setPositiveButton("确定", (dialog, which) -> {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    dialog.dismiss();
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       dialog.dismiss();
                   }
               }).show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    private void startAnimAndCheckWifiState() {
        if (operatingAnim != null) {
            startWifiAnimation();
            checkWifiState();
        }
    }

    private void checkWifiState() {
        new CheckWifiStateTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                WifiStateInfo wifiStateInfo = (WifiStateInfo) o;
                if (!Preconditions.isNullOrEmpty(wifiStateInfo)) {
                    if (CommUtils.isWifiOpen(MyWifiActivity.this)) {
                        String client_mac = wifiStateInfo.client_mac;
                        showWifiName("社区人智慧WiFi");
                        currentTime = System.currentTimeMillis() / 1000;
                        endTime = DateUtils.getTimesNight() / 1000;
                        getWifiAccout(loginBaseInfo.getMobi(), String.valueOf(currentTime), client_mac, String.valueOf(endTime), md5(loginBaseInfo.getMobi() + String.valueOf(currentTime) + client_mac + String.valueOf(endTime) + "2c93cd289b311e5223303b6d153382fe"));
                    } else {
                        showOpenWifiPop();
                    }
                } else {
                    stopWifiAnimation();
                    showWifiState("未连接");
                    showWifiName("当前连接非社区人智慧Wi-Fi");
                }
            }
        }).execute();
    }

    private void getWifiAccout(String phone, String timestamp, String client_mac, String goodsCategoriesId, String sign) {
        new GetWifiAccoutTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                WifiStateInfo wifiStateInfo = (WifiStateInfo) o;
                if (!Preconditions.isNullOrEmpty(wifiStateInfo)) {
                    getWifiPwd(wifiStateInfo.username, DES.decode(wifiStateInfo.encrypted_passwd));
                } else {
                    setWifiConnectResource(R.mipmap.btn_bg_no_connect);
                    stopWifiAnimation();
                    hideWifiTime();
                    showWifiState("未连接");
                    connectStateLogo.setVisibility(View.GONE);
                }
            }
        }).execute(phone, timestamp, client_mac, goodsCategoriesId, sign);
    }

    private void getWifiPwd(String username, String password) {
        new GetWifiPwdTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                isWifiSuccess = true;
                stopWifiAnimation();
                setWifiConnectResource(R.mipmap.btn_bg_connect);
                tvConnectState.setText("连接成功");
                showWifiName("智慧社区WiFi");
                SHelper.vis(connectStateLogo);
                showWifiTime();
                showWifiLastTime();
                updateWifiDay();
            }
        }).execute(username, password);
    }

    private void updateWifiDay() {
        new UpdateWifiDayTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                WifiDayInfo wifiDayInfo = (WifiDayInfo) o;
                if (!Preconditions.isNullOrEmpty(wifiDayInfo)) {
                    tvWifiAllDay.setText("剩余" + wifiDayInfo.getRe_result().getAllDay() + "天");
                }
            }
        }).execute(loginBaseInfo.getMobi());
    }

    private void setWifiConnectResource(int resource) {
        btnConnectWifi.setBackgroundResource(resource);
    }

    private void showWifiState(String wifiState) {
        tvConnectState.setText(wifiState);
    }

    private void showWifiName(String wifiName) {
        communityWifiName.setText(wifiName);
    }

    private void showWifiLastTime() {
        dayMill = DateUtils.getTimesNight();
        currentTimeNow = System.currentTimeMillis();
        lastTime = dayMill - currentTimeNow;
        cvCountdownView.start(lastTime);
    }

    private void stopWifiAnimation() {
        ivRoundAnim.clearAnimation();
        ivRoundAnim.setVisibility(View.GONE);
    }

    private void startWifiAnimation() {
        ivRoundAnim.setVisibility(View.VISIBLE);
        ivRoundAnim.startAnimation(operatingAnim);
    }

    private void hideWifiTime() {
        tvWifiUserTime.setVisibility(View.GONE);
        cvCountdownView.setVisibility(View.GONE);
    }

    private void showWifiTime() {
        tvWifiUserTime.setVisibility(View.VISIBLE);
        cvCountdownView.setVisibility(View.VISIBLE);
    }

    private void offWifiRefreshPage() {
        stopWifiAnimation();
        hideWifiTime();
        showWifiState("未连接");
        SHelper.gone(connectStateLogo);
        showWifiName("社区人智慧WiFi");
        setWifiConnectResource(R.mipmap.btn_bg_no_connect);
        WpToast.l(this, "已成功断开WiFi");
    }

    private void shareWifi() {
        ShareInfo shareInfo = new ShareInfo();
        shareInfo.setLink("http://a.app.qq.com/o/simple.jsp?pkgname=cn.shequren.communityPeople");
        shareInfo.setSubject("智慧社区WiFi");
        shareInfo.setText("新用户注册免费送30天，用社区人app购物就送智慧WiFi使用时长");
        ShareActionReflectUtils.jumpSharerPage(this, shareInfo);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }
}
